package com.example.manager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.manager.domain.R;
import com.example.manager.domain.SysUser;
import com.example.manager.service.SysUserService;
import com.example.manager.utils.JwtUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    SysUserService usersService;

//    @Autowired
//    StringRedisTemplate redisTemplate1;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/login")
    public R<String> login(String username, String password) throws JsonProcessingException {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUsername,username);
        queryWrapper.lambda().eq(SysUser::getPassword,password);
        SysUser user = usersService.getOne(queryWrapper);
        if (user==null){
            return R.fail("账户或密码错误.");
        }
        //根据用户名称生成令牌
        String token = JwtUtils.generateToken(username);
        //我们现在没有导入fastjson，所以使用spring里面默认集成的jackson
//        ObjectMapper objectMapper = new ObjectMapper();
//        redisTemplate1.opsForValue().set("login:"+username,objectMapper.writeValueAsString(user));
        redisTemplate.opsForValue().set("login:"+username,user);
        return R.success(200,"登录成功",token);

    }
}
